package twitter.client.adapter;

import java.util.List;

import twitter.client.R;
import twitter.client.bean.TwitterAccount;
import twitter.client.task.ImageDownloadTask;
import twitter.client.util.ImageChace;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AccountListAdapter extends ArrayAdapter<TwitterAccount> {
	private LayoutInflater infrator;
	private Context context;
	private List<TwitterAccount> listData;
	private int resourceId;

	public AccountListAdapter(Context context, int resourceId,
			List<TwitterAccount> listData) {
		super(context, resourceId, listData);

		this.context = context;
		this.resourceId = resourceId;
		this.listData = listData;
		this.infrator = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(convertView == null){
			convertView = this.infrator.inflate(this.resourceId, null);
		}
		
		View v = convertView;
		
		ImageView profImage = (ImageView)v.findViewById(R.id.accountProfImage);
		TextView accountName = (TextView)v.findViewById(R.id.accountName);
		TextView accountScreenName = (TextView)v.findViewById(R.id.accountScreenName);
		
		TwitterAccount account = listData.get(position);
		String imageUrl = account.getProfileImageUrl();
//		v.setTag(imageUrl);
		
		Bitmap image = ImageChace.getImage(imageUrl);
		profImage.setTag(imageUrl);
		if(image != null){
			profImage.setImageBitmap(image);
		}else{
			profImage.setImageResource(R.drawable.default_prof_image);
			ImageDownloadTask task = new ImageDownloadTask(profImage, this.context);
			task.execute(imageUrl);
		}
		
		accountName.setText(account.getName());
		accountScreenName.setText(account.getScreenName());
		
		return convertView;
	}
}
